package cn.xspace.wnx.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;

import com.xspace.android.xafcommon.base.BaseFragment;
import com.xspace.android.xafcommon.util.EventBusConstant;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.ResourceUtils;
import com.xspace.android.xafcommon.view.sdlv.Menu;
import com.xspace.android.xafcommon.view.sdlv.MenuItem;
import com.xspace.android.xafcommon.view.sdlv.SlideAndDragListView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.xspace.app.view.TitleBar;
import cn.xspace.chatui.bean.MessageEntity;
import cn.xspace.library.bean.Type;
import cn.xspace.library.util.BldNavigation;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.wnx.R;
import cn.xspace.wnx.activity.GroupManagerActivity;
import cn.xspace.wnx.activity.NoticeOrWNXListActivity;
import cn.xspace.wnx.adapter.MessageListAdapter;
import cn.xspace.wnx.db.MessageRecordDao;
import cn.xspace.wnx.db.NoticeDao;
import cn.xspace.wnx.util.Navigator;
import de.greenrobot.event.EventBus;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by liuchen on 2016/10/9.
 */
public class MessageFragment extends BaseFragment implements SlideAndDragListView.OnListItemLongClickListener,
        SlideAndDragListView.OnDragListener, SlideAndDragListView.OnSlideListener,
        SlideAndDragListView.OnListItemClickListener, SlideAndDragListView.OnMenuItemClickListener,
        SlideAndDragListView.OnItemDeleteListener, SlideAndDragListView.OnListScrollListener {

    public static final String TAG = MessageFragment.class.getSimpleName();
    public static final int NOTICE_ITEM = 0;
    public static final int WNX_ITEM = 1;
    public static final int GROUP_ITEM = 2;
    private Menu mMenu;
    private SlideAndDragListView<MessageEntity> mListView;
    //    private ListView mListView;
    private MessageListAdapter mAdapter;
    private ArrayList<MessageEntity> mList;
    private Intent myIntent;

    private boolean isPause = false;

    private String user_id;
    private boolean isFarmer;
    private TitleBar mTitleBar;


    public MessageFragment() {
        EventBus.getDefault().register(this);
    }

    public static MessageFragment newInstance() {
        MessageFragment fragment = new MessageFragment();
//        Bundle args = new Bundle();
//        args.putParcelable("viewPager", mViewPager);
//        args.putString("table_name", table_name);
//        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtil.e(TAG, "wubaojie>>>" + "onResume: ");
        if (isPause) {
            try {
                refreshData();
                isPause = false;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        isPause = true;
    }

    @Override
    public View initView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_message, null);
    }

    @Override
    protected void initFindViewById(View view) {
        mListView = (SlideAndDragListView) view.findViewById(R.id.lv_edit);
        mTitleBar = (TitleBar) view.findViewById(R.id.msg_list_title);
        mTitleBar.setLeftLayoutVisibility(View.GONE);
    }

    @Override
    protected void initEvent() {
        mListView.setOnListItemLongClickListener(this);
        mListView.setOnListItemClickListener(this);
        mListView.setOnSlideListener(this);
        mListView.setOnMenuItemClickListener(this);
        mListView.setOnItemDeleteListener(this);
        mListView.setOnListScrollListener(this);
        mTitleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Navigator.startNewChatActivity(mContext, null);
            }
        });
//        mListView.setPullRefreshEnable(false);
//        mListView.setPullLoadEnable(false);
//        connectInfo.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (netStatue == NetType.OVERLOAD) {
//                    tvConnectInfo.setText(R.string.server_reconnect);
//                    netStatue = NetType.RECONNECTING;
//                    Intent intent = new Intent(mContext, IMChatService.class);
//                    mContext.startService(intent);
//                }
//            }
//        });
    }

    @Override
    public void initData() {
        initMenu();
        user_id = MyInfoUtil.getMyUserid(mContext);
        if ("1".equals(MyInfoUtil.getIsFarmer())) {
            isFarmer = true; //是农民
        }
        mList = new ArrayList<>();
        mListView.setMenu(mMenu);
        showProgressLoading("加载中");
        mAdapter = new MessageListAdapter(mContext, mList);
        mListView.setAdapter(mAdapter);
        mListView.setOnDragListener(this, mList);
        refreshData();
    }

    private void initMenu() {
        mMenu = new Menu(true, true);
//        mMenu.addItem(new MenuItem.Builder().setWidth((int) getResources().getDimension(R.dimen
// .slv_item_bg_btn_width) * 2)
//                .setBackground(ResourceUtils.getDrawable(this, R.drawable.btn_left0))
//                .setText("One")
//                .setTextColor(Color.GRAY)
//                .setTextSize(14)
//                .build());
//        mMenu.addItem(new MenuItem.Builder().setWidth((int) getResources().getDimension(R.dimen
// .slv_item_bg_btn_width))
//                .setBackground(ResourceUtils.getDrawable(this, R.drawable.btn_left1))
//                .setText("Two")
//                .setTextColor(Color.BLACK)
//                .setTextSize((14))
//                .build());
        mMenu.addItem(new MenuItem.Builder().setWidth((int) getResources().getDimension(R.dimen.space_49) + 40)
                .setBackground(ResourceUtils.getDrawable(R.drawable.selector_btn_delete))
                .setText(getString(R.string.delete))
                .setDirection(MenuItem.DIRECTION_RIGHT)
                .setTextColor(Color.WHITE)
                .setTextSize(14)
                .build());
//        mMenu.addItem(new MenuItem.Builder().setWidth((int) getResources().getDimension(R.dimen.space_49) + 40)
//                .setBackground(ResourceUtils.getDrawable(mContext, R.drawable.selector_btn_delete))
//                .setText(getString(R.string.warn_not))
//                .setDirection(MenuItem.DIRECTION_RIGHT)
//                .setTextColor(Color.WHITE)
//                .setTextSize(14)
//                .build());
//        mMenu.addItem(new MenuItem.Builder().setWidth(100)
//                .setBackground(ResourceUtils.getDrawable(mContext, R.drawable.app_logo))
//                .setDirection(MenuItem.DIRECTION_RIGHT)
//                .setIcon(getResources().getDrawable(R.drawable.app_logo))
//                .build());
    }

    /**
     * eventbus消息接受
     *
     * @param map map中包括type和其他字段。type代表消息类型
     *            type:
     *            AlbumActivity  代表相册
     *            File代表附件
     */
    public void onEventMainThread(Map<String, Object> map) {
        Object type = map.get(EventBusConstant.TYPE);
        if (type == null) {
            return;
        }
        if (EventBusConstant.HUANXIN_PUSH.equals(type)) {
            Object bean = map.get(EventBusConstant.HUANXIN_PUSH_BEAN);
            if (bean instanceof MessageEntity) {
                refreshData();
            }
        } else if (EventBusConstant.DELETE_FRIEND_PUSH.equals(type)) {
            if (EventBusConstant.DELETE_FRIEND_FINISH.equals(map.get(EventBusConstant.ACTION_KEY))) {
                //好友关系删除
                refreshData();
            }
        }
    }

    public void refreshData() {
        LogUtil.e(TAG, "wubaojie>>>刷新消息列表");
        registerSubscription(MessageRecordDao.getInstance().getiMessageData().getMessageList()
                .subscribeOn(Schedulers.io())
                .doOnNext(new Action1<List<MessageEntity>>() {
                    @Override
                    public void call(List<MessageEntity> list) {
                        //添加通知公告置顶
                        MessageEntity noticeEntity = MessageRecordDao.getInstance().updateMessageListNoticeContent();
                        if (noticeEntity != null) {
                            list.add(NOTICE_ITEM, noticeEntity);
                        } else {
                            MessageEntity noticeMessage = new MessageEntity();
                            noticeMessage.msg_type = MsgType.NOTICE.toNumber();
                            noticeMessage.isCanSlide = false;
                            list.add(NOTICE_ITEM, noticeMessage);
                        }
                        //添加微农信置顶
                        MessageEntity wnxEntity = MessageRecordDao.getInstance().updateMessageListWNXContent();
                        if (wnxEntity != null) {
                            list.add(WNX_ITEM, wnxEntity);
                        } else {
                            MessageEntity nwnxMessage = new MessageEntity();
                            nwnxMessage.msg_type = MsgType.WNX_MSG.toNumber();
                            nwnxMessage.isCanSlide = false;
                            list.add(WNX_ITEM, nwnxMessage);
                        }
                        if (!isFarmer) { //不是农民添加群组助手,农民没有群组
                            //添加群助手置顶
                            MessageEntity groupEntity = MessageRecordDao.getInstance().updateMessageListGroupContent();
                            if (groupEntity != null) {
                                list.add(GROUP_ITEM, groupEntity);
                            } else {
                                MessageEntity groupMessage = new MessageEntity();
                                groupMessage.msg_type = MsgType.CHAT_CROUP.toNumber();
                                groupMessage.group_type = Type.GroupType.MANAGER;
                                groupMessage.isCanSlide = false;
                                list.add(GROUP_ITEM, groupMessage);
                            }
                        }
                    }
                })
                .map(new Func1<List<MessageEntity>, List<MessageEntity>>() {

                    @Override
                    public List<MessageEntity> call(List<MessageEntity> list) {
                        int noticeCount = NoticeDao.getInstance().getNoticeCount();
                        LogUtil.d(TAG, "wubaojie>>>未读公告: " + noticeCount);
                        list.get(NOTICE_ITEM).msg_unread_count = noticeCount;
                        int wnxCount = NoticeDao.getInstance().getWNXUnreadStatue();
                        list.get(WNX_ITEM).msg_unread_count = wnxCount;
                        int groupCount = NoticeDao.getInstance().getGroupCount();
                        if (!isFarmer) {
                            LogUtil.d(TAG, "wubaojie>>>未读群消息: " + groupCount);
                            list.get(GROUP_ITEM).msg_unread_count = groupCount;
                        }
                        return list;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<MessageEntity>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        dismissProgressLoading();
                    }

                    @Override
                    public void onNext(List<MessageEntity> list) {
                        dismissProgressLoading();
                        mList.clear();
                        mList.addAll(list);
                        LogUtil.d(TAG, "wubaojie>>>listSize: " + list.size() + " list:" + list.toString());

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mAdapter.notifyDataSetChanged();
                            }
                        });

                    }
                }));
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        LogUtil.d(TAG, "setUserVisibleHint " + isVisibleToUser);
    }

    private void setWnxRead() {

        registerSubscription(MessageRecordDao.getInstance().getiMessageData().updateUnreadStatus("", MsgType.WNX_MSG
                .toNumber())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe());
    }

    @Override
    public void onListItemLongClick(View view, int position) {
        Log.i(TAG, "onListItemLongClick   " + position);
    }

    @Override
    public void onDragViewStart(int position) {
        Log.i(TAG, "onDragViewStart   " + position);
    }

    @Override
    public void onDragViewMoving(int position) {
        Log.i("yuyidong", "onDragViewMoving   " + position);
    }

    @Override
    public void onDragViewDown(int position) {
        Log.i(TAG, "onDragViewDown   " + position);
    }

    @Override
    public void onListItemClick(View v, int mPostion) {
        int position = mPostion - mListView.getHeaderViewsCount();
        Log.i(TAG, "onListItemClick   " + position);
        //0：通知公告；1：微农信；2：单聊；3：群助手
        if (mList.get(position).msg_type == 0) {
            myIntent = new Intent(getActivity(), NoticeOrWNXListActivity.class);
            myIntent.putExtra("msg_type", "0");
            myIntent.putExtra("MessageEntity", mList.get(position));
            startActivity(myIntent);
        } else if (mList.get(position).msg_type == 1) {
//            setWnxRead();
//            mList.get(position).msg_unread_count = 0; //不要在这里将未读消息置零进去之后可能还是未读的

            myIntent = new Intent(getActivity(), NoticeOrWNXListActivity.class);
            myIntent.putExtra("msg_type", "1");
            myIntent.putExtra("MessageEntity", mList.get(position));
//            myIntent = new Intent(getActivity(), WnxorgListActivity.class);
            startActivity(myIntent);
        } else if (mList.get(position).msg_type == 2) {
            MessageEntity messageEntity = mList.get(position);
            Bundle dataBundle = new Bundle();
            dataBundle.putString(BldNavigation.SENDER_ID, messageEntity.msg_sender_id);
            dataBundle.putInt(BldNavigation.CHAT_TYPE, messageEntity.msg_type);
            dataBundle.putString(BldNavigation.CHAT_NAME, messageEntity.msg_sender_name);
            dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, "");
            dataBundle.putString(BldNavigation.CHAT_SENDER_SEX, messageEntity.user_sex);
            Navigator.startChatActivity(mContext, dataBundle);
//            Navigator.startChatActivity(mContext, .msg_sender_id, mList.get(position).msg_type, mList.get(position)
// .msg_sender_name,"");
        } else if (mList.get(position).msg_type == 3) {
            if (mList.get(position).group_type != Type.GroupType.TEMP_GROUP) {
                myIntent = new Intent(getActivity(), GroupManagerActivity.class);
                startActivity(myIntent);
            } else {
                MessageEntity messageEntity = mList.get(position);
                Bundle dataBundle = new Bundle();
                dataBundle.putString(BldNavigation.SENDER_ID, messageEntity.msg_group_id);
                dataBundle.putInt(BldNavigation.CHAT_TYPE, messageEntity.msg_type);
                dataBundle.putInt(BldNavigation.GROUP_TYPE, messageEntity.group_type);
                dataBundle.putString(BldNavigation.CHAT_NAME, messageEntity.msg_group_name);
                dataBundle.putString(BldNavigation.CHAT_SENDER_LOGO, "");
                Navigator.startChatActivity(mContext, dataBundle);
//                Bundle dataBundle = new Bundle();
//                dataBundle.putString(Navigator.SENDER_ID, messageEntity.msg_group_id);
//                dataBundle.putInt(Navigator.CHAT_TYPE, messageEntity.msg_type);
//                dataBundle.putString(Navigator.CHAT_NAME, messageEntity.msg_group_name);
//                dataBundle.putString(Navigator.CHAT_SENDER_LOGO, "");
//                Navigator.startChatActivity(mContext, dataBundle);
            }
        }

    }

    @Override
    public void onSlideOpen(View view, View parentView, int position, int direction) {
        Log.i(TAG, "onSlideOpen   " + position);
    }

    @Override
    public void onSlideClose(View view, View parentView, int position, int direction) {
        Log.i(TAG, "onSlideClose   " + position);
    }

    @Override
    public int onMenuItemClick(View v, int itemPosition, int buttonPosition, int direction) {
        Log.i(TAG, "onMenuItemClick   " + itemPosition + "   " + buttonPosition + "   " + direction);
        switch (direction) {
            case MenuItem.DIRECTION_LEFT:
                switch (buttonPosition) {
                    case 0:
                        return Menu.ITEM_NOTHING;
                    case 1:
                        return Menu.ITEM_SCROLL_BACK;
                }
                break;
            case MenuItem.DIRECTION_RIGHT:
                switch (buttonPosition) {
                    case 0:
                        int position = itemPosition;
                        LogUtil.d(position + "");
                        MessageEntity deleteEntity = mList.get(position);
                        mList.remove(position);
                        mAdapter.notifyDataSetChanged();
                        if (deleteEntity.msg_type == MsgType.CHAT_SINGLE.toNumber()) {
                            registerSubscription(MessageRecordDao.getInstance().getiMessageData().deleteSingleChat
                                    (deleteEntity
                                            .msg_sender_id)
                                    .observeOn(Schedulers.io())
                                    .subscribe());
                        } else {
                            registerSubscription(MessageRecordDao.getInstance().getiMessageData().deleteGroupChat
                                    (deleteEntity.msg_group_id)
                                    .observeOn(Schedulers.io())
                                    .subscribe());
                        }
                        return Menu.ITEM_SCROLL_BACK;
                    case 1:
                        return Menu.ITEM_SCROLL_BACK;
                }
        }
        return Menu.ITEM_NOTHING;
    }

    @Override
    public void onItemDelete(View view, int position) {
        LogUtil.d(TAG, "onItemDelete  " + position);
//        mList.remove(position - mListView.getHeaderViewsCount());
//        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        switch (scrollState) {
            case SlideAndDragListView.OnListScrollListener.SCROLL_STATE_IDLE:
                break;
            case SlideAndDragListView.OnListScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                break;
            case SlideAndDragListView.OnListScrollListener.SCROLL_STATE_FLING:
                break;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    }

    private boolean isSingle(MessageEntity pushBean) {
        if (MsgType.CHAT_SINGLE.toNumber() == pushBean.msg_type) {
            return true;
        }
        return false;
    }

    /**
     * 刷新列表的方法
     */

    Subscriber<Integer> unreadCountSub = new Subscriber<Integer>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onNext(Integer intent) {
            dismissProgressLoading();

            LogUtil.d("  更新 UI ");
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mAdapter.notifyDataSetChanged();
                }
            });
        }
    };
}
